
const http = require('http')
const url = require('url')

// 创建应用的过程 创建路由系统
function createApplication(){ //工厂函数
    const router = [
        {
            method:"all",//所以方法都可以匹配到
            pathname:'*', //所有路径都能匹配到
            handler(req,res){
                res.end(`cannot  ${req.method} ${req.url}`)
            }
        }
    ]
    const app = {
        get(pathname,handler ){
            router.push({
                method:'get',
                pathname,
                handler
            })
        },
        listen(){
            const server = http.createServer((req,res)=>{
                let {pathname} = url.parse(req.url)
                let method = req.method.toLowerCase()
                for (let i = 1; i < router.length; i++) {
                    let {method:routeMethod,pathname:routePath,handler} = this.router[i]
                    if(pathname === routePath && method === routeMethod) {
                       return handler(req,res)
                    }
                }
                this.router[0].handler(req,res)
            })
            server.listen(...arguments)
            
        }
    }
    return app
}
module.exports = createApplication